<template>
	<view class="search-page-container">
		<view class="search-bar-fixed" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="search-input-wrapper">
				<u-icon name="search" color="#c0c4cc" size="20"></u-icon>
				<input class="search-input" type="text" v-model="keyword" placeholder="搜索联系人: 昵称" confirm-type="search"
					@input="handleKeywordInput" @confirm="performSearch(true)" :focus="inputFocus" @focus="onInputFocus"
					@blur="onInputBlur" />
				<u-icon v-if="keyword" name="close-circle-fill" color="#c0c4cc" size="20"
					@click="clearKeywordAndResults"></u-icon>
				<!-- <view v-if="!keyword" class="mic-icon-wrapper" @click="handleVoiceSearch">
					<u-icon name="mic" color="#606266" size="22"></u-icon>
				</view> -->
			</view>
			<text class="cancel-button" @click="cancelSearch">取消</text>
		</view>

		<scroll-view scroll-y class="search-content-scroll" :style="{ paddingTop: searchBarHeight + 'px' }"
			@scrolltolower="loadMoreResults">
			<!-- 搜索结果展示 -->
			<view v-if="keyword && searchResults.length > 0" class="search-results-section">
				<view class="results-header">联系人</view>
				<uni-list :border="false">
					<uni-list-item v-for="user in searchResults" :key="user.userId" clickable
						@click="navigateToUserProfile(user)">
						<template v-slot:header>
							<u-avatar :src="user.avatar" size="40" customStyle="margin-right: 20rpx;"
								mode="aspectFill"></u-avatar>
						</template>
						<template v-slot:body>
							<view class="user-info">
								<text class="user-name"
									v-html="highlightKeyword(user.nickName || user.userName, keyword)"></text>
							</view>
						</template>
					</uni-list-item>
				</uni-list>

				<!-- 加载指示 和 没有更多提示 -->
				<view style="padding: 20rpx 0;">
					<u-loadmore v-if="isLoadingMore" status="loading" loadingText="正在加载更多..." />
					<!-- 当不再加载更多 并且 没有更多结果时，显示 "没有更多结果了" -->
					<u-loadmore v-else-if="!hasMoreResults && searchResults.length > 0 && keyword" status="nomore"
						nomoreText="没有更多结果了" line />
					<!-- “更多联系人”链接，仅在还有更多且不在加载时显示 -->
					<view v-else-if="hasMoreResults && searchResults.length > 0 && keyword" class="more-contacts-link"
						@click="loadMoreResults">
						更多联系人 <u-icon name="arrow-right" size="14" color="#828282"></u-icon>
					</view>
				</view>
			</view>

			<!-- 无搜索结果提示 -->
			<u-empty v-if="keyword && searchResults.length === 0 && !isLoadingResults && !isFirstSearch" text="未找到相关用户"
				mode="search" marginTop="40"></u-empty>

			<!-- 最近搜索 (仅当关键词为空时显示) -->
			<view v-if="!keyword" class="recent-searches-section">
				<view class="recent-header">
					<text class="recent-title">最近在搜</text>
					<u-icon name="trash" color="#909399" size="20" @click="confirmClearRecentSearches"></u-icon>
				</view>
				<view class="recent-list" v-if="recentSearches.length > 0">
					<view class="recent-item" v-for="(item, index) in recentSearches" :key="index"
						@click="clickRecentSearch(item)">
						<u-icon name="clock" color="#909399" size="16"></u-icon>
						<text class="recent-text">{{ item }}</text>
					</view>
				</view>
				<view class="no-recent-searches" v-else>
					<text>暂无搜索记录</text>
				</view>
			</view>

			<view v-if="!keyword" class="ai-search-button-wrapper">
				<button class="ai-search-button" @click="handleAiSearch">
					AI搜索 <u-icon name="arrow-right" color="#606266" size="14"></u-icon>
				</button>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import {
		getClientUserList
	} from '@/request/api.js';

	const RECENT_SEARCHES_KEY = 'user_contact_recent_searches';
	const MAX_RECENT_SEARCHES = 10;

	export default {
		data() {
			return {
				keyword: '',
				recentSearches: [],
				inputFocus: false,
				searchResults: [],
				isLoadingResults: false,
				isLoadingMore: false,
				apiPageNum: 1,
				apiPageSize: 15,
				hasMoreResults: true,
				searchDebounceTimer: null,
				statusBarHeight: 0,
				searchBarHeight: 80,
				isFirstSearch: true,
			};
		},
		onLoad() {
			const systemInfo = uni.getSystemInfoSync();
			this.statusBarHeight = systemInfo.statusBarHeight || 0;
			this.$nextTick(() => {
				const query = uni.createSelectorQuery().in(this);
				query.select('.search-bar-fixed').boundingClientRect(data => {
					if (data) {
						this.searchBarHeight = data.height;
					}
				}).exec();
			});
			this.loadRecentSearches();
		},
		onShow() {
			setTimeout(() => {
				this.inputFocus = true;
			}, 100);
		},
		methods: {
			loadRecentSearches() {
				const searches = uni.getStorageSync(RECENT_SEARCHES_KEY);
				if (searches && Array.isArray(searches)) {
					this.recentSearches = searches;
				}
			},
			saveSearchTerm(term) {
				if (!term || term.trim() === '') return;
				let searches = [...this.recentSearches];
				searches = searches.filter(s => s !== term);
				searches.unshift(term);
				if (searches.length > MAX_RECENT_SEARCHES) {
					searches = searches.slice(0, MAX_RECENT_SEARCHES);
				}
				this.recentSearches = searches;
				uni.setStorageSync(RECENT_SEARCHES_KEY, searches);
			},
			handleKeywordInput() {
				this.isFirstSearch = true;
				if (this.searchDebounceTimer) {
					clearTimeout(this.searchDebounceTimer);
				}
				if (!this.keyword.trim()) {
					this.searchResults = [];
					this.hasMoreResults = true;
					return;
				}
				this.searchDebounceTimer = setTimeout(() => {
					this.performSearch(true);
				}, 500);
			},
			async performSearch(isNewSearch = false) {
				if (!this.keyword.trim()) {
					this.searchResults = [];
					return;
				}
				if (isNewSearch) {
					this.apiPageNum = 1;
					this.searchResults = [];
					this.hasMoreResults = true;
				}

				this.isLoadingResults = true;
				this.isFirstSearch = false;

				try {
					const params = {
						nickName: this.keyword,
						pageNum: this.apiPageNum,
						pageSize: this.apiPageSize,
					};
					const res = await getClientUserList(params);
					if (res.data && res.data.code === 200) {
						const newResults = res.data.rows || [];
						if (isNewSearch) {
							this.searchResults = newResults;
						} else {
							this.searchResults = this.searchResults.concat(newResults);
						}
						this.hasMoreResults = newResults.length === this.apiPageSize;
						if (this.hasMoreResults) {
							this.apiPageNum++;
						}
					} else {
						uni.showToast({
							title: res.data.msg || '搜索失败',
							icon: 'none'
						});
						this.hasMoreResults = false;
					}
				} catch (error) {
					console.error('搜索用户失败:', error);
					uni.showToast({
						title: '搜索请求异常',
						icon: 'none'
					});
					this.hasMoreResults = false;
				} finally {
					this.isLoadingResults = false;
					this.isLoadingMore = false;
				}
			},
			loadMoreResults() {
				if (this.hasMoreResults && !this.isLoadingMore && this.keyword.trim()) {
					this.isLoadingMore = true;
					this.performSearch(false);
				}
			},
			clearKeywordAndResults() {
				this.keyword = '';
				this.searchResults = [];
				this.hasMoreResults = true;
				this.isFirstSearch = true;
			},
			handleVoiceSearch() {
				uni.showToast({
					title: '语音搜索功能暂未实现',
					icon: 'none'
				});
			},
			cancelSearch() {
				uni.navigateBack();
			},
			confirmClearRecentSearches() {
				if (this.recentSearches.length === 0) return;
				uni.showModal({
					title: '提示',
					content: '确定要清空最近搜索记录吗？',
					success: (res) => {
						if (res.confirm) this.clearRecentSearches();
					},
				});
			},
			clearRecentSearches() {
				this.recentSearches = [];
				uni.removeStorageSync(RECENT_SEARCHES_KEY);
			},
			clickRecentSearch(term) {
				this.keyword = term;
				this.performSearch(true);
				this.saveSearchTerm(term);
			},
			handleAiSearch() {
				uni.showToast({
					title: 'AI搜索功能暂未实现',
					icon: 'none'
				});
			},
			navigateToUserProfile(user) {
				this.saveSearchTerm(this.keyword)
				// uni.navigateTo({
				// 	url: `/pages/user/others/others?userId=${user.userId}`,
				// });
				const userParam = {
					userId: user.userId,
					nickName: user.nickName,
					avatar: user.avatar,
				};
				uni.navigateTo({
					url: `/pages_sub/user/chat/chat?user=${JSON.stringify(userParam)}&group=false`
				});
			},
			highlightKeyword(text, keyword) {
				if (!text) return '';
				if (!keyword || keyword.trim() === '') return text;
				const regex = new RegExp(`(${this.escapeRegExp(keyword)})`, 'gi');
				return text.replace(regex, '<span style="color: #2979ff;">$1</span>');
			},
			escapeRegExp(string) {
				return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
			},
			onInputFocus() {
				this.inputFocus = true;
			},
			onInputBlur() {
				// this.inputFocus = false; 
			}
		},
	};
</script>

<style lang="scss" scoped>
	.search-page-container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #fff;
	}

	.search-bar-fixed {
		position: fixed;
		top: 20rpx;
		left: 0;
		right: 0;
		z-index: 100;
		display: flex;
		align-items: center;
		padding: 16rpx 24rpx;
		background-color: #fff;
		border-bottom: 1rpx solid #e8e8e8;
	}

	.search-input-wrapper {
		flex-grow: 1;
		display: flex;
		align-items: center;
		background-color: #f0f0f0;
		border-radius: 30rpx;
		padding: 0 20rpx;
		height: 68rpx;

		.search-input {
			flex-grow: 1;
			height: 100%;
			padding: 0 12rpx;
			font-size: 28rpx;
			color: #303133;
			caret-color: $u-primary;
		}

		.mic-icon-wrapper {
			padding-left: 16rpx;
			border-left: 1rpx solid #e0e0e0;
			margin-left: 16rpx;
			display: flex;
			align-items: center;
			height: 36rpx;
		}
	}

	.cancel-button {
		margin-left: 24rpx;
		font-size: 30rpx;
		color: #303133;
		white-space: nowrap;
	}

	.search-content-scroll {
		flex-grow: 1;
		background-color: #ffffff;
	}

	.search-results-section {
		.results-header {
			padding: 20rpx 30rpx;
			font-size: 26rpx;
			color: #909399;
			background-color: #f8f8f8;
		}

		.user-info {
			display: flex;
			flex-direction: column;
			justify-content: center;

			.user-name {
				font-size: 30rpx;
				color: #303133;
			}
		}

		.more-contacts-link {
			padding: 24rpx 30rpx;
			text-align: center;
			font-size: 28rpx;
			color: #507daf;
			border-top: 1rpx solid #f0f0f0; // 与列表项分隔
			border-bottom: 1rpx solid #f0f0f0; // 与下方loadmore分隔
		}

		::v-deep .uni-list-item__container {
			padding-top: 20rpx !important;
			padding-bottom: 20rpx !important;
		}
	}

	.recent-searches-section {
		padding: 30rpx;

		.recent-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 24rpx;

			.recent-title {
				font-size: 28rpx;
				color: #606266;
			}
		}

		.recent-list {
			display: flex;
			flex-wrap: wrap;
			gap: 20rpx;

			.recent-item {
				display: flex;
				align-items: center;
				background-color: #f4f4f4;
				padding: 12rpx 20rpx;
				border-radius: 24rpx;
				font-size: 26rpx;
				color: #303133;

				.recent-text {
					margin-left: 8rpx;
				}
			}
		}

		.no-recent-searches {
			color: #909399;
			font-size: 26rpx;
			text-align: center;
			padding: 20rpx 0;
		}
	}

	.ai-search-button-wrapper {
		margin-top: 60rpx;
		display: flex;
		justify-content: center;

		.ai-search-button {
			background-color: #f0f0f0;
			color: #303133;
			border: none;
			border-radius: 36rpx;
			font-size: 28rpx;
			padding: 18rpx 40rpx;
			display: flex;
			align-items: center;
			line-height: 1.5;

			&::after {
				border: none;
			}
		}
	}
</style>